package com.abocode.aichat.app.auth;


import com.abocode.aichat.app.constant.ErrorCode;
import com.abocode.aichat.app.exception.ContextRuntimeException;
import com.abocode.aichat.app.utils.EncryptionUtils;
import com.abocode.aichat.app.utils.StringUtil;
import com.abocode.aichat.app.vo.AuthorizationVo;
import com.abocode.aichat.app.vo.HttpHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by guanxf on 2015/12/16.
 */
//@Component
public class AuthUnloginInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private HttpHelper httpHelper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (HandlerMethod.class.getSimpleName().equals(handler.getClass().getSimpleName())) {
             String requestData = httpHelper.getRequestBody(request);
            String data = "";

            if (!StringUtil.isNullOrEmpty(requestData)) {
                try {
                    data=EncryptionUtils.toBASE64ToDES(requestData);
                }catch (Exception e){
                    throw new ContextRuntimeException(ErrorCode.COMM_INVALID_REQUEST, String.format("非法请求data is %s", data));
                }
            }

            AuthorizationVo av = httpHelper.getAuthorizationVo(request);//鉴权
            if (!av.getData().equals(EncryptionUtils.toMD5(data))) {
                throw new ContextRuntimeException(ErrorCode.COMM_INVALID_REQUEST, String.format("非法请求data is %s", data));
            }


            String authorization = EncryptionUtils.toMD5(av.getData() + av.getAppid() + av.getVersion() + av.getDtype() + av.getAppid() + av.getData() + av.getDtype());
            if (!authorization.equals(av.getAuthorization())) {
                throw new ContextRuntimeException(ErrorCode.COMM_INVALID_REQUEST, String.format("非法请求authorization is %s", authorization));
            }


        }
        request.setAttribute("time", System.currentTimeMillis());
        return super.preHandle(request, response, handler);
    }
}
